
# 脚本实现启停程序

date "+%Y:%m:%d:%H:%M:%S"

# 更新配置文件
confStr=`cat ./config.ini`
isSqlStr=`echo "${confStr}" | sed "s/#df_flag#/${dnFlg}/g"`





# 从网卡抓数据需要root权限，加sudo
sudo /tmp/tmp.FdUHWCPhyb/bin/Network_Traffic_Processing




#include <pcap.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>

class CompareTraffic {
public:
    void writeTraffic1(const struct pcap_pkthdr *header) {
        std::cout << "Writing traffic for packet captured at time: " << header->ts.tv_sec << "." << header->ts.tv_usec << std::endl;
        std::cout << "Packet length: " << header->len << " bytes" << std::endl;
    }
};

// 回调函数，用于处理每个捕获的数据包
void packet_handler(u_char *user_data, const struct pcap_pkthdr *pkthdr, const u_char *packet) {
    // user_data 可以用于传递用户数据，这里传递的是 CompareTraffic 对象的指针
    CompareTraffic *compareTraffic = reinterpret_cast<CompareTraffic*>(user_data);

    // 打印数据包的基本信息
    std::cout << "Packet captured at time: " << pkthdr->ts.tv_sec << "." << pkthdr->ts.tv_usec << std::endl;
    std::cout << "Packet length: " << pkthdr->len << " bytes" << std::endl;

    // 调用 CompareTraffic 的成员函数
    compareTraffic->writeTraffic1(pkthdr);

    // 打印前几个字节的数据包内容
    for (int i = 0; i < 16 && i < pkthdr->len; ++i) {
        printf("%02x ", packet[i]);
    }
    printf("\n");
}

int main(int argc, char *argv[]) {
    char errbuf[PCAP_ERRBUF_SIZE]; // 错误缓冲区
    pcap_t *handle; // pcap 句柄
    const char *dev = argv[1]; // 网卡设备名称
    CompareTraffic compareTraffic; // 创建 CompareTraffic 对象

    if (argc != 2) {
        fprintf(stderr, "Usage: %s <device>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    // 打开指定的网卡设备
    handle = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf);
    if (handle == nullptr) {
        fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
        exit(EXIT_FAILURE);
    }

    // 设置过滤器（可选）
    struct bpf_program fp;
    char filter_exp[] = "ip"; // 过滤IP数据包
    if (pcap_compile(handle, &fp, filter_exp, 0, PCAP_NETMASK_UNKNOWN) < 0) {
        fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(handle));
        exit(EXIT_FAILURE);
    }
    if (pcap_setfilter(handle, &fp) < 0) {
        fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(handle));
        exit(EXIT_FAILURE);
    }

    // 使用 pcap_loop 捕获数据包
    if (pcap_loop(handle, 10, packet_handler, reinterpret_cast<u_char*>(&compareTraffic)) < 0) {
        fprintf(stderr, "pcap_loop failed: %s\n", pcap_geterr(handle));
        exit(EXIT_FAILURE);
    }

    // 关闭 pcap 句柄
    pcap_close(handle);

    return 0;
}
















